<?php
/**
 * Description of userController
 *
 * @author Henson
 */
class userController{
	
    public function indexAction()
    {
		$user = new User();
		$totalNum = $user->getUserTotal();
		$p = isset($_GET['p']) ? intval($_GET['p']) : 1;
		$pageUrl = '/index.php?r=user';
		$page = new Page($p, $pageUrl, $totalNum, $user->pageRow);
		$where = "where del='0'";
		$orderBy = 'order by update_time desc, id desc';
		$limit = " limit ".($p -1 ) * $user->pageRow .",".$user->pageRow;
		$rows = $user->getUserList($where, $orderBy, $limit);
		foreach($rows as $key=>$value)
		{
			$rows[$key] = $user->dealUser($value);
		}
		$pageInfo['rows'] = $rows;
		$pageInfo['page'] = $page;
		$view = new view(); 
		$view->showPage('management/userList.tpl.htm', $pageInfo);
    }
	
	public function registerAction()
	{
		global $_CFG;
		$this->checkRegister();
		$insertArr = array();
		$insertArr['title'] = @intval(trim($_POST['title']));
		$insertArr['first_name'] = @htmlspecialchars(trim($_POST['first_name']), ENT_QUOTES);
		$insertArr['last_name'] = @htmlspecialchars(trim($_POST['last_name']), ENT_QUOTES);
		$insertArr['password'] = @md5(htmlspecialchars(trim($_POST['password']), ENT_QUOTES));
		$insertArr['country'] = @intval(trim($_POST['country']));
		$insertArr['province'] = @htmlspecialchars(trim($_POST['province']), ENT_QUOTES);
		$insertArr['address'] = @htmlspecialchars(trim($_POST['address']), ENT_QUOTES);
		$insertArr['email'] = @htmlspecialchars(trim($_POST['email']), ENT_QUOTES);
		$insertArr['home_phone'] = @htmlspecialchars(trim($_POST['home_phone']), ENT_QUOTES);
		$insertArr['cell_phone'] = @htmlspecialchars(trim($_POST['cell_phone']), ENT_QUOTES);
		$insertArr['postal_code'] = @intval(trim($_POST['postal_code']));
		$insertArr['encorecard'] = @intval(trim($_POST['encorecard']));
		$insertArr['confirmcode'] = md5($_CFG['secretKey'].$insertArr['email']);
		//$insertArr['creditcard'] = @htmlspecialchars(trim($_POST['creditcard']), ENT_QUOTES);
		$user = new User();
		$uid = $user->insertUser($insertArr);
		if($uid > 0)
		{
			$mailContent = array(
				"email"	=> $insertArr['email'],
				"name"	=> $insertArr['first_name'],
				"subject"	=> "用户注册验证",
				"body"	=> "尊敬的用户：
					欢迎您的注册，请点击<a href=\"http://www.reservation.com/index.php?r=user/regconfirm&uid={$uid}&regconfirm={$insertArr['confirmcode']}\">http://www.reservation.com/index.php?r=user/regconfirm&uid={$uid}&regconfirm={$insertArr['confirmcode']}</a>此链接完成注册！"
			);
			_sendMail($mailContent);
			header("Location: /login.html");die;
		}
		else
		{
			_errorShow("back");
		}
	}
	
	public function regconfirmAction()
	{
		$uid = @intval($_GET['uid']);
		$regconfirm = @htmlspecialchars(trim($_GET['regconfirm']), ENT_QUOTES);
		if(!preg_match('#^[0-9a-f]{32}$#i', $regconfirm))
		{
			echo "<script>alert('验证不成功！');window.location.href='http://www.reservation.com'</script>";die;
		}
		else
		{
			$updateArr = array();
			$updateArr['status'] = '1';
			$user = new User();
			$user->updateUser($updateArr, $uid);
			echo "<script>alert('验证成功！');window.location.href='http://www.reservation.com/login.html'</script>";die;
		}
	}
	
	public function showProvinceAction()
	{
		global $_CFG;
		$country = @intval($_POST['country']);
		if($country == 1 || $country == 2)
		{
			$province = $_CFG['province'][$country];
			echo json_encode($province);
		}
		die;
	}

	public function loginAction()
	{
		global $_CFG;
		$email = @htmlspecialchars(trim($_POST['email']), ENT_QUOTES);
		$password =  @md5(htmlspecialchars(trim($_POST['password']), ENT_QUOTES));
		$user = new User();
		$userInfo = $user->getUserByEmail($email);
		if($userInfo && $password == $userInfo['password'])
		{
			if($userInfo['status'] == 0)
			{
				_errorShow("您注册的账号还未邮箱验证！");
			}
			else
			{
				setcookie("uid", $userInfo['id']);
				setcookie("username", $userInfo['first_name']);
				setcookie("auth", md5($_CFG['secretKey'].$userInfo['id']));
				setcookie("vip", $userInfo['vip']);
				setcookie("encorecard", ($userInfo['encorecard'] > 0 ? '1' : '0'));
				setcookie("creditcard", ($userInfo['creditcard'] != "" ? '1' : '0'));
				header("Location: /index.html");die;
			}
		}
		else
		{
			_errorShow("the user name and password don't match.");
		}
	}
	
	public function logoutAction()
	{
		setcookie("uid", "", -7200);
		setcookie("username", "", -7200);
		setcookie("auth", "", -7200);
		setcookie("vip", "", -7200);
		setcookie("encorecard", "", -7200);
		setcookie("creditcard", "", -7200);
		header("Location: /index.html");die;
	}
	
	public function checkCardAction()
	{
		if(_checkLogin())
		{
			$eid = @intval($_GET['eid']);
			if($eid == 0)
			{
				echo "invalid";die;
			}
			$event = new Event();
			$eventInfo = $event->getEventByEid($eid);
			$uid = $_COOKIE['uid'];
			$user = new User();
			$userInfo = $user->getUserByUid($uid);
			//$checkCard = 1;
			if($eventInfo['type'] == '1' && $userInfo['vip'] == '0')
			{
				$post_encorecard = @intval($_GET['encorecard']);
				if($post_encorecard > 0)
				{
					if($user->checkVip($post_encorecard))
					{
						$updateArr = array();
						$updateArr['vip'] = '1';
						$updateArr['encorecard'] = $post_encorecard;
						if($user->updateUser($updateArr, $uid))
						{
							$userInfo['encorecard'] = $post_encorecard;
							setcookie("encorecard", '1');
							setcookie("vip", '1');
							echo "success";
							die;
						}
						else
						{
							echo "VIP会员未更新！";
							die;
						}
					}
					else
					{
						echo "你还不是VIP会员";
						die;
					}
				}
				else
				{
					echo "未提交积分卡";
					die;
				}
			}
			if($eventInfo['n_encorecard'] == '1' && $userInfo['encorecard'] == '0')
			{
				$get_encorecard = @intval($_GET['encorecard']);
				if( $get_encorecard > 0)
				{
					$updateArr = array();
					$updateArr['encorecard'] = $get_encorecard;
					if(!$user->updateUser($updateArr, $uid))
					{
						setcookie("encorecard", '1');
						echo "success";
						die;
					}
					else
					{
						echo "用户信息更新失败！";
						die;
					}
				}
				else
				{
					echo "encorecard is invalid";
					die;
				}
			}
			if($eventInfo['n_creditcard'] == '1' && $userInfo['creditcard'] == '')
			{
				$get_creditcard = @htmlspecialchars($_GET['creditcard'], ENT_QUOTES);
				if($get_creditcard > 0 && _checkCreditCard($get_creditcard))
				{
					$updateArr = array();
					$updateArr['creditcard'] = $get_creditcard;
					if(!$user->updateUser($updateArr, $uid))
					{
						setcookie("creditcard", '1');
						echo "success";
						die;
					}
					else
					{
						echo "用户信息更新失败！";
						die;
					}
				}
				else
				{
					echo "creditcard is invalid";
					die;
				}
			}
			
			echo "success";die;
			
		}
		else
		{
			echo "please login";
			die;
		}
	}

	public function checkRegister($flag=1)
	{
		$regArr = array(
			"first_name" => "#^[a-zA-Z ']{1,50}$#",
			"last_name" => "#^[a-zA-Z ']{1,50}$#",
			"password" => "#^\w{1,20}$#",
			"confirm_password" => "same||password",
			"address" => "null||#^.{1,255}$#",
			"home_phone" => "null||#^\d{3}-\d{7}$#",
			"cell_phone" => "null||#^\d{3}-\d{7}$#",
			"email" => "null||#^[0-9a-zA-Z@\._]{1,100}$#",
			"postal_code" => "null||#^\d{5}$#",
			"encorecard" => "null||#^\d{1,}$#"
		);
		foreach ($_POST as $key=>$item)
		{
			if(!$flag&&($key=="password"||$key=="confirm_password")&&$item==""){
				continue;
			}
			if(array_key_exists($key, $regArr))
			{
				$tempArr = explode('||', $regArr[$key]);
				if(count($tempArr) == 2)
				{
					if($tempArr[0] == "same")
					{
						if($item != $_POST[$tempArr[1]])
						{
							_errorShow("{$key} is invalid");
						}
					}
					elseif($tempArr[0] == "null")
					{
						if($item != "")
						{
							if(!preg_match($tempArr[1], $item))
							{
								_errorShow("{$key} is invalid");
							}
						}
					}
				}
				else
				{
					if(!preg_match($regArr[$key], $item))
					{
						_errorShow("{$key} is invalid");
					}
				}
			}
		}
	}
	
	public function forgetpwAction()
	{
		global $_CFG;
		$email = @htmlspecialchars($_POST['email'], ENT_QUOTES);
		$user = new User();
		$userInfo = $user->getUserByEmail($email);
		if($userInfo)
		{
			$forgetcode = md5($_CFG['secretKey'].$userInfo['email'].time());
			$url = "http://www.reservation.com/index.php?r=user/resetpw&uid=".$userInfo['id']."&forgetcode=".$forgetcode;
			$mailContent = array(
				'email' => $email,
				'name'	=> $userInfo['first_name'],
				'subject'=> '重置密码',
				'body'	=> "请点击<a href='{$url}'>{$url}</a>链接，完成密码重置！"		
			);
			$updateArr['forgetcode'] = $forgetcode;
			$user->updateUser($updateArr, $userInfo['id']);
			_sendMail($mailContent);
			_showMessage("注意查收邮件，完成密码重置", "http://www.reservation.com/");
		}
	}
	
	public function resetpwAction()
	{
		global $_CFG;
		$uid = @intval($_GET['uid']);
		$forgetcode = @htmlspecialchars(trim($_GET['forgetcode']), ENT_QUOTES);
		if($uid > 0)
		{
			$user = new User();
			$userInfo = $user->getUserByUid($uid);
			if($userInfo['forgetcode'] == $forgetcode)
			{
				$view = new View();
				$pageInfo['uid'] = $uid;
				$pageInfo['forgetcode'] = $forgetcode;
				$view->showPage('resetpw.tpl.htm', $pageInfo);
			}
			else
			{
				_showMessage("重置密码错误！", "http://www.reservation.com/");
			}
		}
		else
		{
			_showMessage("重置密码错误！", "http://www.reservation.com/");
		}
	}
	
	public function resetpwdoAction()
	{
		$uid = @intval($_POST['uid']);
		$forgetcode = @htmlspecialchars(trim($_POST['forgetcode']), ENT_QUOTES);
		$password = @htmlspecialchars(trim($_POST['password']), ENT_QUOTES);
		if(!preg_match('#^\w{1,20}$#i', $password))
		{
			_showMessage("重置密码错误！", "http://www.reservation.com/");
		}
		$user = new User();
		$userInfo = $user->getUserByUid($uid);
		if($userInfo['forgetcode'] == $forgetcode)
		{
			$updateArr = array();
			$updateArr['password'] = md5($password);
			if($user->updateUser($updateArr, $uid))
			{
				_showMessage("重置密码成功！", "http://www.reservation.com/login.html");
			}
			else
			{
				_showMessage("重置密码错误！", "http://www.reservation.com/");
			}
		}
		else
		{
			_showMessage("重置密码错误！", "http://www.reservation.com/");
		}
	}
	public function accountAction()
	{
		if(_checkLogin()){
			$uid = $_COOKIE['uid'];
			$user = new User();
			$userInfo = $user->getUserByUid($uid);
			$userInfo = $user->dealUser($userInfo);
			$pageInfo['row'] = $userInfo;
			$view = new view(); 
			$view->showPage('account.tpl.htm', $pageInfo);			
		}else{
			_showMessage("请先登陆", "/login.html");
		}
	}
	public function modifyAction()
	{
		global $_CFG;
		if(_checkLogin()){
			$uid = $_COOKIE['uid'];
			$user = new User();
			$userInfo = $user->getUserByUid($uid);
			$pageInfo['row'] = $userInfo;
			$arr_email=explode("@",$userInfo['email']);
			$pageInfo['row']['email1']=$arr_email[0];
			$pageInfo['row']['email2']=$arr_email[1];
			$arr_home_phone=explode("-",$userInfo['home_phone']);
			$pageInfo['row']['home_phone1']=$arr_home_phone[0];
			$pageInfo['row']['home_phone2']=$arr_home_phone[1];
			$arr_cell_phone=explode("-",$userInfo['cell_phone']);
			$pageInfo['row']['cell_phone1']=$arr_cell_phone[0];
			$pageInfo['row']['cell_phone2']=$arr_cell_phone[1];
			$pageInfo['row']['email1']=$arr_email[0];
			$pageInfo['row']['email2']=$arr_email[1];
			$pageInfo['title']=$_CFG['userTitle'];
			$pageInfo['country']=$_CFG['country'];
			$province=$_CFG['province'][$userInfo['country']];
			$arr=array();
			foreach($province as $k=>$val){
				$arr[$val]=$val;
			}
			$pageInfo['province']=$arr;
			$view = new view(); 
			$view->showPage('user_modify.tpl.htm', $pageInfo);			
		}else{
			_showMessage("请先登陆", "/login.html");
		}
	}
	public function saveAction()
	{
		global $_CFG;
		if(_checkLogin()){
			$uid = $_COOKIE['uid'];
			$this->checkRegister(0);
			$updateArr = array();
			$updateArr['title'] = @intval(trim($_POST['title']));
			$updateArr['first_name'] = @htmlspecialchars(trim($_POST['first_name']), ENT_QUOTES);
			$updateArr['last_name'] = @htmlspecialchars(trim($_POST['last_name']), ENT_QUOTES);
			if(trim($_POST['password'])){
				$updateArr['password'] = @md5(htmlspecialchars(trim($_POST['password']), ENT_QUOTES));
			};
			$updateArr['country'] = @intval(trim($_POST['country']));
			$updateArr['province'] = @htmlspecialchars(trim($_POST['province']), ENT_QUOTES);
			$updateArr['address'] = @htmlspecialchars(trim($_POST['address']), ENT_QUOTES);
			$updateArr['email'] = @htmlspecialchars(trim($_POST['email']), ENT_QUOTES);
			$updateArr['home_phone'] = @htmlspecialchars(trim($_POST['home_phone']), ENT_QUOTES);
			$updateArr['cell_phone'] = @htmlspecialchars(trim($_POST['cell_phone']), ENT_QUOTES);
			$updateArr['postal_code'] = @intval(trim($_POST['postal_code']));
			$updateArr['encorecard'] = @intval(trim($_POST['encorecard']));
			$updateArr['confirmcode'] = md5($_CFG['secretKey'].$updateArr['email']);
			$user = new User();
			$uid = $user->updateUser($updateArr,$uid);
			if($uid > 0)
			{
				header("Location: /index.php?r=user/account");die;
			}
			else
			{
				_errorShow("back");
			}
		}else{
			_showMessage("请先登陆", "/login.html");
		}
	}
}

?>
